package cn.geminis.workflow.service.service.model;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.net.URI;

/**
 * @author puddi
 */
@Import(FeignClientsConfiguration.class)
@RequiredArgsConstructor
@Service
public class RemoteDataService {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private final RemoteDataClient client;

    @SneakyThrows
    public <T> T get(String url, Class<T> clazz) {
        try {
            var value = client.get(new URI(url));
            return OBJECT_MAPPER.readValue(value, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("获取数据错误", e);
        }
    }

    public void run(String url, String value) {
//        var client = this.builder.target(RemoteDataClient.class, url);
//        try {
//            client.run(new URI(url), JSONObject.parseObject(value));
//        } catch (URISyntaxException e) {
//            throw new RuntimeException("URL地址错误", e);
//        }
    }

    @FeignClient(name = "RemoteDataClient")
    private interface RemoteDataClient {

        /**
         * 获取远程数据
         *
         * @return 数据
         */
        @GetMapping
        @LoadBalanced
        String get(URI uri);

        /**
         * 调用远程数据
         *
         * @param value 更新数据
         */
        @PutMapping
        @LoadBalanced
//        @Headers({"Content-Type: application/json"})
        void run(URI uri, @RequestBody Object value);

    }
}
